<script setup>
import { addNewUser, fetchVerifyCode } from '@/service'
import { useAppStore } from '@/stores'

const appStore = useAppStore()

const emit = defineEmits(['update:modelValue'])
function toLogin() {
  emit('update:modelValue', 'login')
}
const isRead = ref(false)
const formRef = ref()
const rPasswordFormItemRef = ref(null)
const formValue = ref({
  username: null,
  password: null,
  reenteredPassword: null,
  code: null
})
const rules = {
  username: [
    {
      required: true,
      validator(_, value) {
        if (!value) {
          return new Error('请输入用户名')
        } else if (!/^[\w-]{4,16}$/.test(value)) {
          return new Error('用户名应由字母与数字组成, 长度应为4-16位, 且不能带有 _ - 外的符号')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码'
    }
  ],
  reenteredPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input'
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: ['input', 'blur']
    },
    {
      validator: async (_, value) => {
        const res = await fetchVerifyCode({
          code: value
        })
        return new Promise((resolve, reject) => {
          if (res.message === '验证码正确') {
            resolve()
          } else {
            resetCode()
            reject(new Error('验证码错误,请重新输入'))
          }
        })
      },
      message: '验证码错误,请重新输入',
      trigger: ['blur']
    }
  ]
}
const codeUrl = ref(`/api/code?theme=${appStore.colorMode}`)

function validatePasswordStartWith(_, value) {
  return !!formValue.value.password && formValue.value.password.startsWith(value) && formValue.value.password.length >= value.length
}

function validatePasswordSame(_, value) {
  return value === formValue.value.password
}

function handlePasswordInput() {
  if (formValue.value.reenteredPassword) {
    rPasswordFormItemRef.value?.validate({ trigger: 'password-input' })
  }
}

function handleValidateButtonClick(e) {
  e.preventDefault()
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      const res = await addNewUser({
        username: formValue.value.username,
        password: formValue.value.password,
      })
      if (res.data === 'User exists') return window.$message.error('用户名已存在, 请重新输入用户名')
      window.$message.success('注册成功，请登录')
      toLogin()
    } else {
      return window.$message.error(errors[0][0].message)
    }
  })
}

function areFieldsValid() {
  return formValue.value.username !== null && formValue.value.password !== null && formValue.value.reenteredPassword !== null && formValue.value.code !== null && formValue.value.username.trim() !== '' && formValue.value.password.trim() !== '' && formValue.value.reenteredPassword.trim() !== '' && formValue.value.code.trim() !== '' && isRead.value
}

function resetCode() {
  const url = new URL(codeUrl.value, window.location.origin) // 完整的 URL，包括域名
  // 更新或添加 't' 参数
  url.searchParams.set('t', Date.now().toString())
  // 更新 codeUrl 的值
  codeUrl.value = url.toString() // 保存更新后的 URL
}

watch(
  () => appStore.colorMode,
  () => {
    codeUrl.value = `/api/code?theme=${appStore.colorMode}`
  },
  { immediate: true }
)
</script>

<template>
  <div>
    <n-h2 depth="3" class="text-center">注册</n-h2>
    <n-form ref="formRef" :show-label="false" size="large" :model="formValue" :rules="rules">
      <n-form-item path="username" label="用户名">
        <n-input v-model:value="formValue.username" @keydown.enter.prevent placeholder="输入用户名" />
      </n-form-item>
      <n-form-item path="password" label="密码">
        <n-input v-model:value="formValue.password" type="password" @input="handlePasswordInput" @keydown.enter.prevent placeholder="输入密码" />
      </n-form-item>
      <n-form-item ref="rPasswordFormItemRef" first path="reenteredPassword" label="重复密码">
        <n-input v-model:value="formValue.reenteredPassword" :disabled="!formValue.password" type="password" @keydown.enter.prevent placeholder="请再次输入密码" />
      </n-form-item>
      <n-form-item first path="code" label="验证码">
        <div style="display: flex; justify-content: space-between; width: 100%">
          <n-input v-model:value="formValue.code" @keydown.enter.prevent placeholder="验证码" style="width: 150px" />
          <img @click="resetCode" :src="codeUrl" alt="" />
        </div>
      </n-form-item>
      <n-form-item>
        <n-space vertical :size="20" class="w-full">
          <n-checkbox v-model:checked="isRead">
            我已阅读并同意
            <n-button type="primary" text>用户协议</n-button>
          </n-checkbox>
          <n-button :disabled="!areFieldsValid()" type="primary" attr-type="button" block @click="handleValidateButtonClick">注册</n-button>
          <n-flex justify="center">
            <n-text>已有账号?</n-text>
            <n-button text type="primary" @click="toLogin">登录</n-button>
          </n-flex>
        </n-space>
      </n-form-item>
    </n-form>
  </div>
</template>
